<?php
class ManageController extends Zend_Controller_Action
{
    /**
     * 进入控制器的时候查看客户端是否存在cookie
     * 如果存在验证通过直接分配session
     * 否则走到客户端指定的控制器
     * @see Zend_Controller_Action::init()
     */
    public function init()
    {
    	parent::init();
    	
    	$actionName = $this->_request->getActionName();
    	$notCheck = array('index', 'login', 'logout');    	
        $cookieName = Zend_Registry::get('database')->admin->cookie;
        if (isset($_COOKIE[$cookieName])) {
            $authObj = new Business_Manage_Auth();
            $cookieResult = $authObj->validateAuthSignature(
                $_COOKIE[$cookieName]
            );
            if ($cookieResult['errorcode'] == 0) {
                $authObj->setUserLogin($cookieResult['result']);
            }
        }
        if (!in_array($actionName, $notCheck)) {
        	$authObj = new Business_Manage_Auth();
        	if (!$authObj->isLogin()) {
        		$this->_redirect('/manage/index');
        	}
        }
    }
    
    /**
     * 管理员登陆界面
     * 如果登陆直接进入homepage管理页
     */
    public function indexAction()
    {
        $this->view->title = 'iLOVE管理员登录';
        $authObj = new Business_Manage_Auth();
        if ($authObj->isLogin()) {
            $this->_redirect('/manage/homepage');
        }
    }
    
    /**
     * 用户登陆验证action
     * 如果用户名密码正确直接分配session
     * 如果有选择记住我，就分配cookie
     * 成功之后跳转到homepage管理页
     */
    public function loginAction()
    {
        $username = $this->_request->getParam('username');
        $password = $this->_request->getParam('password');
        $rememberme = $this->_request->getParam('rememberme');
        if (isset($username) && isset($password) && $username != "" &&
         $password != "") {
            $authObj = new Business_Manage_Auth();
            $authResult = $authObj->checkLogin($username, $password);
            if ($authResult['errorcode'] == 0) {
                if (isset($rememberme)) {
                    $cookieName = Zend_Registry::get('database')->admin->cookie;
                    $cookie = $authObj->generateAuthSignature(
                        $authResult['result'], 
                        $authObj->getCookieExpireTime()
                    );
                    setcookie(
                        $cookieName,
                        $cookie, 
                        $authObj->getCookieExpireTime()
                    );
                }
                $authObj->setUserLogin($authResult['result']);
                $this->_redirect('/manage/homepage');
            } else {
                $this->view->errormsg = '<div id="login_error">登录失败！</div>';
                $this->render('index');
            }
        } else {
            $this->view->errormsg = '<div id="login_error">登录失败！</div>';
            $this->render('index');
        }
    }
    
    /**
     * 所有文章列表
     */
    public function articleListAction()
    {
    	$view = $this->view;
    	$view->title = 'iLOVE Admin - Article List';
    	$view->level1 = 'article';
    	$view->level2 = 'list';
    	
    	$view->page = $page = $this->_request->getParam('page', 1);
    	
    	$article = new Business_Article();
    	
    	$view->rowCount = $rowCount = 10;
    	$amount = $article->getArticleAmount(0);
    	$orderby = Zend_Registry::get('config')->page->orderby;
    	$view->total = $total = ceil($amount / $rowCount);
    	//页码超过范围处理
    	if ($page < 1) {
    		$view->page = $page = 1;
    	}
    	if ($page > $total) {
    		$view->page = $page = $total;
    	}
    		
    	$articleList = $article->getArticleList(0, $page, $rowCount, $orderby);
    	
    	$view->articleList = $articleList;
    	//作者信息
    	$authorObj = new Business_Author();
    	$view->author = $authorObj->getAllAuthors();
    	//分类信息
    	$view->categories = Zend_Registry::get('config')->menu;
    }
    
    public function authorListAction()
    {
    	$view = $this->view;
    	$view->title = 'iLOVE Admin - Author List';
    	$view->level1 = 'author';
    	$view->level2 = 'list';
    	
    	$author = new Business_Author();
    	$view->authors = $author->getAllAuthors();
    }
    
    public function deleteArticleAction()
    {
    	$view = $this->view;
    	$aid = $this->_request->getParam('aid', 0);
    	$article = new Business_Article();
    	$result = $article->delete($aid);
    	$this->_helper->getHelper('Json')->sendJson($result);
    }
    
    public function editArticleAction()
    {
    	$view = $this->view;
    	$view->level1 = 'article';
    	$view->level2 = 'edit';
    	$view->title = 'iLOVE Admin - Edit Article';
    	$id = $this->_request->getParam('id', 0);
    	$tableInfo = Zend_Registry::get('database')->article;
    	//基本信息
    	$authorObj = new Business_Author();
    	$view->authors = $authorObj->getAllAuthors();
    	$view->categories = Zend_Registry::get('config')->menu;
    	
    	$article = new Business_Article();
    	$articleDetail = $article->getArticleDetails($id);
    	if ($articleDetail[$tableInfo->keywords] != '') {
    		$articleDetail[$tableInfo->keywords] = explode(',', $articleDetail[$tableInfo->keywords]);
    	} else {
    		$articleDetail[$tableInfo->keywords] = array();
    	}
    	if (!$articleDetail) {
    		$tabeInfo = Zend_Registry::get('database')->article;
    		$articleDetail = array(
    				$tabeInfo->id => 0,
    				$tabeInfo->title => '',
    				$tabeInfo->description => '',
    				$tabeInfo->keywords => array(),
    				$tabeInfo->content => '',
    				$tabeInfo->coverimage => '',
    				$tabeInfo->type => 1,
    				$tabeInfo->author => 1,
    				$tabeInfo->url => null
    		);
    	}
    	$view->article = $articleDetail;
    }
    
    /**
     * 编辑作者
     */
    public function editAuthorAction()
    {
    	$view = $this->view;
    	$view->level1 = 'author';
    	$view->level2 = 'edit';
    	$view->title = 'iLOVE Admin - Edit Author';
    	$id = $this->_request->getParam('id', 0);
    	//基本信息
    	$authorObj = new Business_Author();
    	$author = $authorObj->getAuthorName($id);
    	 
    	if (!$author) {
    		$tabeInfo = Zend_Registry::get('database')->author;
    		$author = array(
    			$tabeInfo->id => 0,
    			$tabeInfo->author => '',
    			$tabeInfo->userid => 0
    		);
    	}
    	$view->author = $author;
    }
    
    /**
     * 发布文章（节点）页面
     * 包括登陆验证
     */
    public function saveArticleAction()
    {
    	$view = $this->view;
    	$view->title = 'iLOVE Admin - Edit Article';
        $authObj = new Business_Manage_Auth();
        $authResult = $authObj->validateAuthSignature();
        //提交后的处理
        $article = new Business_Article();
        //接收提交的信息
        $id = $this->_request->getParam('id', 0);
        $title = $this->_request->getParam('title', '');
        $description = $this->_request->getParam('description', '');
        $keywords = $this->_request->getParam('keywords', '');
        $keywords = implode(',', $keywords);
        $content = $this->_request->getParam('content', '');
		$coverimage = $this->_request->getParam('coverimage', '');
		$type = $this->_request->getParam('type', 1);
        $author = $this->_request->getParam('author', 1);
        //处理组成视频音乐的url字段
        $resType = $this->_request->getParam('resType');
        $resTitle = $this->_request->getParam('resTitle');
        $resAddress = $this->_request->getParam('resAddress');
        
        $resCount = count($resType);
        //有添加音乐视频
       	if (is_array($resType) && $resCount) {
       		//如果是音乐
       		if ($type == 5) {
       			$urlToSave = array();
       			for ($i = 0; $i < $resCount; $i++) {
       				if ($resType[$i] == 'local') {
           				$urlToSave[$resType[$i]][] = array(
           					'title'	=> $resTitle[$i],
           					'url'	=> $resAddress[$i]
           				);
       				} else {
       					$urlToSave[$resType[$i]][] = $resAddress[$i];
       				}
       			}
       			$urlToSave = json_encode($urlToSave);
       		} elseif ($type == 6) {
       			$urlToSave = isset($resAddress[0]) ? $resAddress[0] : '';
       			$urlToSave = json_encode($urlToSave);
       		} else {
       			$urlToSave = null;
       		}
       	} else {
       	    $urlToSave = null;
       	}
       	
        //组成要插入数据库的数组
        $tabeInfo = Zend_Registry::get('database')->article;
        $data = array(
        	$tabeInfo->id => $id,
        	$tabeInfo->title => $title,
        	$tabeInfo->description => strip_tags($description),
        	$tabeInfo->keywords => strip_tags($keywords),
        	$tabeInfo->content => $content,
        	$tabeInfo->coverimage => $coverimage,
        	$tabeInfo->type => $type,
        	$tabeInfo->author => $author,
        	$tabeInfo->url => $urlToSave
        );
        //数据库操作
		$result = $article->save($data);
		if ($result['errorcode']) {
			$view->errorcode = $result['errorcode'];
			$view->errormsg = '增加/修改成功';
		} else {
        	$view->errorcode = $result['errorcode'];
        	$view->errormsg = $result['errormsg'];
        }
    }
    
    /**
     * 保存作者
     * 包括登陆验证
     */
    public function saveAuthorAction()
    {
    	$view = $this->view;
    	$view->title = 'iLOVE Admin - Edit Author';
    		//提交后的处理
    		$authorObj = new Business_Author();
    		//接收提交的信息
    		$id = $this->_request->getParam('id', 0);
    		$author = $this->_request->getParam('author', '');
    		$userid = $this->_request->getParam('userid', 0);
    		//组成要插入数据库的数组
    		$tabeInfo = Zend_Registry::get('database')->author;
    		$data = array(
    			$tabeInfo->id => $id,
    			$tabeInfo->author => $author,
    			$tabeInfo->userid => $userid,
    		);
    		//数据库操作
    		$result = $authorObj->save($data);
    		$view->errormsg = $result['errormsg'];
    }
    
    /**
     * homepage管理页面
     * 包括登陆验证
     */
    public function homepageAction()
    {
    	$view = $this->view;
    	$view->level1 = 'page';
    	$view->level2 = 'home';
    	
        $authObj = new Business_Manage_Auth();
        $view->title = 'iLOVE管理网站首页';
        $homepageObj = new Business_Manage_Homepage();
        list($slider, $sliderTable, $modules, $modulesTable) = $homepageObj->getSliderAndModules();
        $view->slider = $slider;
        $view->sliderTable = $sliderTable;
        $view->modules = $modules;
        $view->modulesTable = $modulesTable;
    }
    
    /**
     * 用户退出action
     * 退出之后跳转到首页
     */
    public function logoutAction()
    {
        $authObj = new Business_Manage_Auth();
        $authObj->logout();
        $authObj->deleteCookie();
        $this->_redirect('/manage');
    }
    
    public function testAction()
    {
        $authObj = new Business_Manage_Auth();
        $this->view->title = 'iLOVE管理网站首页';
        $rtn = $authObj->getUserInfoBySession();
        if ($rtn['errorcode'] == 0) {
            $this->view->username = $rtn['result']['username'];
        } else {
            $this->_redirect('/manage');
        }
    }
    
    /**
     * 修改首页模块信息的action
     */
    public function modHomepageModulesAction()
    {
        $form = $this->_request->getParams();
        unset($form['controller']);
        unset($form['action']);
        unset($form['module']);
        $content = array();
        $homepageObj = new Business_Manage_Homepage();
        $tableMaps = $homepageObj->getHomepageModulesTableInfo();
        foreach ($form as $key => $value) {
            $content[$tableMaps->$key] = $value;
        }
        $rtn = $homepageObj->updateHomepageModules($content);
        $this->view->errormsg = $rtn['errormsg'];
        list($slider, $sliderTable, $modules, $modulesTable) = $homepageObj->getSliderAndModules();
        $this->view->slider = $slider;
        $this->view->sliderTable = $sliderTable;
        $this->view->modules = $modules;
        $this->view->modulesTable = $modulesTable;
        $this->render('homepage');
    }
    
    /**
     * 修改首页slider信息的action
     */
    public function modHomepageSliderAction()
    {
        $form = $this->_request->getParams();
        unset($form['controller']);
        unset($form['action']);
        unset($form['module']);
        $homepageObj = new Business_Manage_Homepage();
        $tableMaps = $homepageObj->getHomepageSliderTableInfo();
        $amount = count($form);
        $content = array();
        for ($i = 1; $i <= $amount / 4; $i++) {
            if ($form['imageUrl' . $i] != null) {
                $content[] = array(
                    $tableMaps->title => $form['title' . $i],
                    $tableMaps->description => $form['description' . $i],
                    $tableMaps->detailUrl => $form['detailUrl' . $i],
                    $tableMaps->imageUrl => $form['imageUrl' . $i]
                );
            }
        }
        if (count($content) != 0) {
            $rtn = $homepageObj->updateHomepageSlider($content);
            $this->view->errormsg = $rtn['errormsg'];
        } else {
            $this->view->errormsg = 'Nothing submitted!';
        }
        list($slider, $sliderTable, $modules, $modulesTable) = $homepageObj->getSliderAndModules();
        $this->view->slider = $slider;
        $this->view->sliderTable = $sliderTable;
        $this->view->modules = $modules;
        $this->view->modulesTable = $modulesTable;
        $this->render('homepage');
    }
    /**
     * 模版完整页面
     */
    public function newAction()
    {
    	
    }
    
    public function mostViewedAction()
    {
    	$view = $this->view;
    	$view->level1 = 'widgets';
    	$view->level2 = 'mostviewed';
    	$view->title = 'iLOVE Admin - Most Viewed';
    	$view->mostviewed = Business_MostViewed::getInstance()->getAll();
    }
    
    /**
     * 保存浏览最多图片轮转
     */
    public function saveMostviewedAction()
    {
    	$view = $this->view;
    	$form = $this->_request->getParams();
    	unset($form['controller']);
        unset($form['action']);
        unset($form['module']);
        $fields = array_keys($form);
        $count = count($form[$fields[0]]);
        $dealForm = array();
        $result = array();
        for ($i = 0; $i < $count; $i++) {
        	foreach ($fields as $value) {
        		$dealForm[$i][$value] = $form[$value][$i];
        	}
        	$result[] = Business_MostViewed::getInstance()->save($dealForm[$i]);
        }
        if (in_array(false, $result)) {
        	$view->errorcode = -1;
        	$view->errormsg = '修改失败';
        } else {
        	$view->errorcode = -0;
			$view->errormsg = '修改成功';
        }
    }
    
    public function otherPagesAction()
    {
        $view = $this->view;
        $view->level1 = 'page';
        $view->level2 = 'other';
        $view->title = 'iLOVE Admin - Other Pages';
        $view->otherpages = Business_Page::getInstance()->getAllPages();
    }
    
    public function saveOtherPagesAction()
    {
        $view = $this->view;
        $form = $this->_request->getParams();
        unset($form['controller']);
        unset($form['action']);
        unset($form['module']);
        $fields = array_keys($form);
        $count = count($form[$fields[0]]);
        $dealForm = array();
        $result = array();
        for ($i = 0; $i < $count; $i++) {
            foreach ($fields as $value) {
                $dealForm[$i][$value] = $form[$value][$i];
            }
            $pageTable = Zend_Registry::get('database')->page;
            $dealForm[$i][$pageTable->mtime] = date('c');
            $result[] = Business_Page::getInstance()->savePage($dealForm[$i]);
        }
        if (in_array(false, $result)) {
            $view->errorcode = -1;
            $view->errormsg = '修改失败';
        } else {
            $view->errorcode = 0;
            $view->errormsg = '修改成功';
        }
        $this->_redirect(APPLICATION_URL . '/manage/other-pages');
    }
    
    public function compressCssAction()
    {
        //include global homepage ilove style footer
        $files = Zend_Registry::get('config')->compress->css;
        $fileArr = explode(',', $files);
        $content = '';
        foreach ($fileArr as $file) {
            $filename = PROJECT_ROOT . CSS_MIN_PATH . $file;
            $content .= file_get_contents($filename);
        }
        echo $content;
        file_put_contents(PROJECT_ROOT . CSS_MIN_PATH . '/main.css', $content);
        exit;
    }
}